//
//  YBNetworking.m
//  iphoneLive
//
//  Created by YunBao on 2018/6/6.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "YBNetworking.h"
#import "AFNetworking.h"
#import "CSJADLoading.h"

@implementation YBNetworking
+ (instancetype)share{
    static YBNetworking *netWorking;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        netWorking = [[self alloc] init];
        netWorking.manager = [AFHTTPSessionManager manager];
        
        netWorking.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        netWorking.manager.requestSerializer.timeoutInterval = 15;
        // 响应类型
        netWorking.manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",@"image/png", @"multipart/form-data",@"image/jpeg",@"application/octet-stream",@"application/xml",@"text/event-stream",nil];
    });
    return netWorking;
}
+ (void)postUploadFileWithUrl:(NSString *)url Dic:(NSMutableDictionary *)dic fileData:(NSData *)fileData Suc:(PullSuccessBlock)sucBack{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"requestTime" object:nil];
    AFHTTPSessionManager *session = [YBNetworking share].manager;
    [dic setObject:@"ios" forKey:@"source"];
    [dic setObject:@"zh" forKey:@"language"];
    
    [session POST:url parameters:[PublicObj reqeustHandleParams:dic] headers:[PublicObj getNetworkingHeaders] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:fileData name:dic[@"key"] fileName:fileName mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject == nil){
            NSLog(@"%@",url);
        }
        id result = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
        result = AFJSONObjectByRemovingKeysWithNullValues(result, NSJSONReadingFragmentsAllowed);
        
        if([result[@"code"] intValue] == 200){
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
        }else if ([result[@"code"] intValue] == 104){
            [SVProgressHUDTool dismiss];
            if([QZUserInfoModel share].onceLogin == NO){
                NSLog(@"请求的url===%@",url);
                [QZUserInfoModel share].onceLogin = YES;
                [[BSystemAlert shared] showAlertWithTitle:@"温馨提示" message:@"登录过期，请重新登录" userData:nil cancelTitle:@"知道了" actions:@[] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
                    if([actionTitle isEqualToString:@"知道了"]){
                        [CSJADLoading dj_SignOutWithPaySecretKey];
                        [QZUserInfoModel cleanUserData];
                    }
                }];
            }
        }else{
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString * str = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
        NSDictionary * errDic = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
        NSLog(@"%@",errDic);
        sucBack(nil,-1001,@"网络超时~");
    }];
}
+(void)postWithUrl:(NSString *)url Dic:(NSMutableDictionary *)dic Suc:(PullSuccessBlock)sucBack{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"requestTime" object:nil];
    AFHTTPSessionManager *session = [YBNetworking share].manager;
    [dic setObject:@"ios" forKey:@"source"];
    [dic setObject:@"zh" forKey:@"language"];
    [session POST:url parameters:[PublicObj reqeustHandleParams:dic] headers:[PublicObj getNetworkingHeaders]  progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if(responseObject == nil){
            NSLog(@"%@",url);
        }
        id result = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
        result = AFJSONObjectByRemovingKeysWithNullValues(result, NSJSONReadingFragmentsAllowed);
        
        if([result[@"code"] intValue] == 200){
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
            if([[QZUserInfoModel share].feedbackTotal intValue] != [result[@"feedbackTotal"] intValue]){
                [QZUserInfoModel share].feedbackTotal = result[@"feedbackTotal"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"feedbackTotalNotifitiaon" object:nil];
            }
        }else if ([result[@"code"] intValue] == 104){
            [SVProgressHUDTool dismiss];
            if([QZUserInfoModel share].onceLogin == NO){
                NSLog(@"请求的url===%@",url);
                [QZUserInfoModel share].onceLogin = YES;
                [[BSystemAlert shared] showAlertWithTitle:@"温馨提示" message:@"登录过期，请重新登录" userData:nil cancelTitle:@"知道了" actions:@[] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
                    if([actionTitle isEqualToString:@"知道了"]){
                        [CSJADLoading dj_SignOutWithPaySecretKey];
                        [QZUserInfoModel cleanUserData];
                    }
                }];
            }
        }else{
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString * str = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
        NSDictionary * errDic = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
        NSLog(@"%@",errDic);
        sucBack(nil,-1001,@"网络超时~");
    }];
}
+ (void)postFeedBackUploadUrl:(NSString *)url Dic:(NSMutableDictionary *)dic images:(NSArray *)images Suc:(PullSuccessBlock)sucBack{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"requestTime" object:nil];
    [dic setObject:@"ios" forKey:@"source"];
    [dic setObject:@"zh" forKey:@"language"];
    
    AFHTTPSessionManager *manager = [YBNetworking share].manager;
    [manager POST:url parameters:[PublicObj reqeustHandleParams:dic] headers:[PublicObj getNetworkingHeaders] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSInteger i = 0; i < images.count; i++) {
            UIImage *image = images[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,arc4random_uniform(1000)];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"file%d",arc4random_uniform(1000)] fileName:fileName mimeType:@"image/jpeg"]; //
        }
        
    } progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            id result = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
            result = AFJSONObjectByRemovingKeysWithNullValues(result, NSJSONReadingFragmentsAllowed);
            
            if([result[@"code"] intValue] == 200){
                sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
            }else if ([result[@"code"] intValue] == 104){
                [SVProgressHUDTool dismiss];
                if([QZUserInfoModel share].onceLogin == NO){
                    NSLog(@"请求的url===%@",url);
                    [QZUserInfoModel share].onceLogin = YES;
                    [[BSystemAlert shared] showAlertWithTitle:@"温馨提示" message:@"登录过期，请重新登录" userData:nil cancelTitle:@"知道了" actions:@[] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
                        if([actionTitle isEqualToString:@"知道了"]){
                            [CSJADLoading dj_SignOutWithPaySecretKey];
                            [QZUserInfoModel cleanUserData];
                        }
                    }];
                }
            }else{
                sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
            }
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            sucBack(nil,-1001,@"网络超时~");
        });
    }];
}
+ (void)postCreatorInfoUrl:(NSString *)url Dic:(NSMutableDictionary *)dic shenfengzhengFrontImage:(NSData *)frontImageData shenfengzhengBackImage:(NSData *)backImageData fuzhuImages:(NSArray *)images Suc:(PullSuccessBlock)sucBack{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"requestTime" object:nil];
    AFHTTPSessionManager *session = [YBNetworking share].manager;
    [dic setObject:@"ios" forKey:@"source"];
    [dic setObject:@"zh" forKey:@"language"];
    [session POST:url parameters:[PublicObj reqeustHandleParams:dic] headers:[PublicObj getNetworkingHeaders] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 身份证正面
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *imageFileName = [NSString  stringWithFormat:@"%@%@%d.jpg", str,[QZUserInfoModel share].mid,arc4random_uniform(1000)];
        [formData appendPartWithFileData:frontImageData name:@"idcard_front" fileName:imageFileName mimeType:@"image/jpeg"];
        
        // 身份证反面
        NSString *str1 = [formatter stringFromDate:[NSDate date]];
        NSString *imageFileName1 = [NSString  stringWithFormat:@"%@%@%d.jpg", str1,[QZUserInfoModel share].mid,arc4random_uniform(1000)];
        
        [formData appendPartWithFileData:backImageData name:@"idcard_back" fileName:imageFileName1 mimeType:@"image/jpeg"];
        
        // 辅助资料
        for (NSInteger i = 0; i < images.count; i++) {
            UIImage *image = images[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@%d.jpg", dateString,arc4random_uniform(1000)];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            NSString *name = [NSString stringWithFormat:@"auxiliary_image_%li",i+1];
            [formData appendPartWithFileData:imageData name:name fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
        result = AFJSONObjectByRemovingKeysWithNullValues(result, NSJSONReadingFragmentsAllowed);
        
        if([result[@"code"] intValue] == 200){
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
        }else if ([result[@"code"] intValue] == 104){
            [SVProgressHUDTool dismiss];
            if([QZUserInfoModel share].onceLogin == NO){
                NSLog(@"请求的url===%@",url);
                [QZUserInfoModel share].onceLogin = YES;
                [[BSystemAlert shared] showAlertWithTitle:@"温馨提示" message:@"登录过期，请重新登录" userData:nil cancelTitle:@"知道了" actions:@[] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
                    if([actionTitle isEqualToString:@"知道了"]){
                        [CSJADLoading dj_SignOutWithPaySecretKey];
                        [QZUserInfoModel cleanUserData];
                    }
                }];
            }
        }else{
            sucBack(result[@"data"],[result[@"code"] intValue],result[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString * str = [[NSString alloc]initWithData:data encoding: NSUTF8StringEncoding];
        NSDictionary * errDic = [PublicObj responseDataWithAES:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
        NSLog(@"%@",errDic);
        sucBack(nil,-1001,@"网络超时~");
    }];
}
@end
